//
//  BangUserAccount.swift
//  bang
//
//  Created by mba on 16/11/2.
//  Copyright © 2016年 mbalib. All rights reserved.
//

import Foundation
import ObjectMapper
import SwiftUI
//import WechatKit

fileprivate let userTokenKey = "userTokenKey"
fileprivate let userInfoKey = "userInfoKey"

class AIUserAccount :ObservableObject{
    
    @AppStorage("isLogin") var isLogin: Bool = false
    
//    @Published var accessTokenModel:AccessTokenModel?
//    
//    init(accessTokenModel: AccessTokenModel) {
//        self.accessTokenModel = accessTokenModel
//    }
    
//    @Published var hasAccessToken = !(AIUserAccount.shared?.accessToken?.isEmpty ?? true)
    /// 判断是否登录
    class var hasAccessToken: Bool {
        return !(AIUserAccount.shared?.accessToken?.isEmpty ?? true)
    }
    
    class var accessToken:String? {
        return AIUserAccount.shared?.accessToken
    }
    class var loginToken:String? {
        return AIUserAccount.shared?.loginToken
    }
    
    class var vip: Bool {
        return hasAccessToken && (AIUserAccount.userInfo != nil) && AIUserAccount.userInfo!.vip
    }
    
    /**
     1. 偏好设置(小) - Xcode 8 beta 无效！
     2. 沙盒- 归档／plist/`json`
     3. 数据库(FMDB/CoreData)
     4. 钥匙串访问(小／自动加密 - 需要使用框架 SSKeychain)
     */
    class func saveAccount(userAccount: AccessTokenModel) {
        
        // 1. 模型转字典
        let dict = userAccount.toJSONString()
        
        UserDefaults.standard.set(dict, forKey: userTokenKey)
    }
    
    class func cleanAccount() {
        UserDefaults.standard.removeObject(forKey: userTokenKey)
        UserDefaults.standard.removeObject(forKey: userInfoKey)
//        MBACache.removeString(key: kUserLoginToken)
//        MBACache.removeString(key: kUserAccessToken)
//        MBACache.removeString(key: kUserName)
//        MBACache.removeString(key: kUserAvator)
//        WechatManager.sharedInstance.logout()
    }
    
    
    class func saveUserInfo(userInfo: UserModel) {
        // 1. 模型转字典
        let dict = userInfo.toJSONString()
        UserDefaults.standard.set(dict, forKey: userInfoKey)
    }
    
    static var userInfo: UserModel? {
        if let usersString = UserDefaults.standard.string(forKey: userInfoKey){
            let userModel = Mapper<UserModel>().map(JSONString: usersString)
            return userModel
        }else {
            return nil
        }
        
    }
    
    static var shared: AccessTokenModel? {
        if let usersString = UserDefaults.standard.string(forKey: userTokenKey){
            let accessTokenModel = Mapper<AccessTokenModel>().map(JSONString: usersString)
            return accessTokenModel
        }else {
            return nil
        }
        
    }
}
